package com.hotstrip.web;

import com.hotstrip.model.R;
import com.hotstrip.model.enums.ResponseCodeEnums;
import com.linecorp.bot.client.LineMessagingClient;
import com.linecorp.bot.model.response.BotApiResponse;
import com.linecorp.bot.model.richmenu.RichMenuListResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * Created by Administrator on 2019/7/31.
 */
@Controller
public class RichMenuController {
    private static Logger logger = LoggerFactory.getLogger(RichMenuController.class);

    @Resource
    private LineMessagingClient lineMessagingClient;

    /**
     * 加载 RichMenu 列表页面
     * @return
     */
    @GetMapping("/richmenu/list")
    public String richMenu(Model model){
        CompletableFuture<RichMenuListResponse> call = lineMessagingClient.getRichMenuList();
        RichMenuListResponse richMenuListResponse = null;
        try {
            richMenuListResponse = call.get();
        } catch (InterruptedException | ExecutionException e) {
            logger.error("request api [/richmenu/list] failed, msg: {}", e.getMessage());
            model.addAttribute("msg", "load data failed");
        }
        if (richMenuListResponse != null)
            model.addAttribute("list", richMenuListResponse.getRichMenus());
        return "richmenu/list";
    }

    /**
     * 删除单个菜单
     * @param richMenuId
     * @return
     */
    @ResponseBody
    @PostMapping("/richmenu/delete")
    public Object delete(String richMenuId){
        if (StringUtils.isEmpty(richMenuId)){
            logger.error("删除 RichMenu 接口失败...无效的 richMenuId");
            return R.error(ResponseCodeEnums.INVALID_PARAM.getValue(), "无效的 richMenuId");
        }
        CompletableFuture<BotApiResponse> call = lineMessagingClient.deleteRichMenu(richMenuId);
        try {
            BotApiResponse response = call.get();
            return R.ok("删除成功");
        } catch (InterruptedException | ExecutionException e) {
            logger.error("删除 RichMenu 接口失败......msg: {}", e.getMessage());
            return R.error(ResponseCodeEnums.INVALID_PARAM.getValue(), "删除菜单失败");
        }
    }
}
